<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="搜索" left-arrow @click-left="$router.back()" />
    <!-- 搜索栏 -->
    <van-search
      v-model="value"
      shape="round"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <van-cell-group>
      <van-cell
        v-for="(item, index) in gaoliang"
        :key="index"
        icon="search"
        @click="$router.push({ path: '/searchjg', query: { sea: sslist[index] } })"
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell-group>
      <van-cell title="历史记录" />
      <van-cell v-for="(item, index) in jllist" :key="index" :title="item">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="close" class="search-icon" @click="scClick" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { sous, sousjl, scsousjl } from "./home.js";
export default {
  name: "seach",
  data() {
    return {
      value: "",
      sslist: [],
      jllist: [],
      itemId: null,
    };
  },
  async created() {
    // 获取搜索记录
    let res = await sousjl();
    this.jllist = res.data.data.keywords;
  },
  methods: {
    // 添加搜索记录
    async onSearch() {
      if (this.value == "") return;
      this.jllist.push(this.value);
      this.value = "";
      this.$router.push({ path: "/searchjg", query: { sea: value } });
    },
    // 删除搜索记录
    async scClick() {
      let res = await scsousjl();
      this.jllist = [];
    },
    // 推荐词功能
    async onInput() {
      clearTimeout(this.itemId);
      this.itemId = setTimeout(async () => {
        if (this.value == "") {
          this.sslist = [];
          return;
        }
        let res = await sous(this.value);
        this.sslist = res.data.data.options;
      }, 300);
    },
  },
  computed: {
    // 推荐词高亮
    gaoliang() {
      let res = new RegExp(this.value, "gi");
      return this.sslist.map((arr) =>
        arr.replace(res, (val) => `<span style="color:red">${val}</span>`)
      );
    },
  },
};
</script>

<style>
</style>